package com.heima.media.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.common.dto.ResponseResult;
import com.heima.media.entity.WmSensitive;
import com.heima.media.service.IAuditService;
import com.heima.media.service.IWmSensitiveService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

@RestController
@RequestMapping("/test")
public class TestController {

    @Autowired
    private IAuditService auditService;


    @GetMapping("/audit/{id}")
    public ResponseResult audit(@PathVariable("id") Integer id) {
        auditService.audit(id);
        return ResponseResult.okResult();
    }


    @Autowired
    private IWmSensitiveService sensitiveService;

    /**
     * 从excel中读取敏感词更新到数据库
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public ResponseResult upload(MultipartFile file) throws Exception {

        EasyExcel.read(file.getInputStream(), WmSensitive.class, new PageReadListener<WmSensitive>(sensitiveList -> {
            for (WmSensitive sensitive : sensitiveList) {
//                先判断这个敏感词是否已存在
                LambdaQueryWrapper<WmSensitive> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(WmSensitive::getSensitives, sensitive.getSensitives());
//                WmSensitive one = sensitiveService.getOne(queryWrapper);
//                if(one==null){
                int count = sensitiveService.count(queryWrapper);
                if (count == 0) {
                    sensitive.setCreatedTime(new Date());
                    sensitiveService.save(sensitive);
                }
            }
        })).sheet().doRead();
        return ResponseResult.okResult();
    }


    @PostMapping("/download")
    public void download(HttpServletResponse response) throws Exception {

        ServletOutputStream outputStream = response.getOutputStream();

        //        一个流：文件输出流
        //        两个头： 1、文件的打开方式 inline  attachment  2、文件的mime类型
        response.setHeader("content-disposition", "attachment;filename=Sensitive.xlsx");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        // 这里 需要指定写用哪个class去写，然后写到第一个sheet，名字为模板 然后文件流会自动关闭
        // 如果这里想使用03 则 传入excelType参数即可
        EasyExcel.write(outputStream, WmSensitive.class)
                .sheet("敏感词")
                .doWrite(() -> {
                    // 分页查询数据
                    return sensitiveService.list();
                });
    }
}
